package mao.leetcode.others.leetcode111;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
     //叶子节点，左右孩子节点都为空的情况才算是。递归算法
    int mindepth = Integer.MAX_VALUE;
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        minDepth_helper(root,1);
        return mindepth;
    }
    public void minDepth_helper(TreeNode root,int level){
        if (root == null) return;
        if (root.left == null && root.right == null){
            if (level < mindepth) mindepth=level;
        }else {
            minDepth_helper(root.left,level+1);
            minDepth_helper(root.right,level+1);
        }
    }

    //使用广度优先算法 ,不必遍历所有节点
    //二叉树深度遍历用栈，宽度遍历用队列。
    public int minDepth_1(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        int min_depth = 1;
        int size;
        if (root == null) return 0;
        queue.offer(root);
        while (queue != null){
            size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null){
                    return min_depth;
                }else {
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
            }
            min_depth++;
        }
        return min_depth;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}
